package com.zsrt.devbase.common.aspect.service;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zsrt.devbase.common.annotation.Paging;
import com.zsrt.devbase.common.utils.ConstantDefine;
import com.zsrt.devbase.dto.BaseDTO;

/**
 *分页处理切面
 */
@Aspect
@Order(2)
public class PagingAspect {
	private Logger logger = Logger.getLogger(this.getClass());
	
	public PagingAspect(){
		logger.info("创建分页处理切面");
	}

	@SuppressWarnings("unchecked")
	@Around("execution(* com.zsrt.devbase.service.*.*(..)) &&  @annotation(com.zsrt.devbase.common.annotation.Paging)")
	public Object paging(ProceedingJoinPoint jp) throws Throwable {
		MethodSignature methodSignature = (MethodSignature) jp.getSignature();
		Method method = methodSignature.getMethod();
		Paging annotation = method.getAnnotation(Paging.class);
		//total 为false，表示布查总记录条数
		boolean total = annotation.total();
		//reasonable 为true表示分页合理化
		boolean reasonable = annotation.reasonable();
		Object[] args = jp.getArgs();
		BaseDTO baseDTO = null;
		if (null != args && args.length > 0) {
			//取出第一个符合要求的实体
			for (int i = 0; i < args.length; i++) {
				if (args[i] instanceof BaseDTO) {
					baseDTO = (BaseDTO) args[i];
					break;
				}
			}
			if (null != baseDTO) {
				//分页查询，查总数
				PageHelper.startPage(baseDTO.getPage(), baseDTO.getRows(),total,reasonable);
				//调用目标对象
				Map<String,Object> result = (Map<String, Object>) jp.proceed(args);
		        List<?> list = (List<?>) result.get(ConstantDefine.ROWS);
		        PageInfo<?> pageInfo = new PageInfo<>(list);
		        //返回数据
				result.put(ConstantDefine.TOTAL, pageInfo.getTotal());		
				result.put(ConstantDefine.PAGINATION, pageInfo); 
				logger.info("查询结果："+result);
				// 以改变后的参数去执行目标方法，并保存目标方法执行后的返回值
				return result;
			}else{
				return jp.proceed();
			}
			
		}else{
			return jp.proceed();
		}
		
	}
}
